import 'package:moonmate/services/shared_preferences_service.dart';

class UserService {
  final SharedPreferencesService _prefsService;

  UserService() : _prefsService = SharedPreferencesService() {
    _prefsService.initialize();
  }

  Future<bool> registerUser(Map<String, dynamic> userData) async {
    try {
      // 添加创建时间和ID
      final completeUserData = {
        'id': DateTime.now().millisecondsSinceEpoch.toString(),
        ...userData,
        'created_at': DateTime.now().toIso8601String(),
        'updated_at': DateTime.now().toIso8601String(),
      };

      // 存储用户数据
      return await _prefsService.setObject(SharedPreferencesService.keyUser, completeUserData);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  Future<Map<String, dynamic>?> loginUser(String email, String password) async {
    try {
      // 在本地存储中查找用户
      final user = _prefsService.getObject(SharedPreferencesService.keyUser);
      if (user != null && user['email'] == email && user['password'] == password) {
        return user;
      }
      return null;
    } catch (e) {
      // 移除print语句，返回null表示操作失败
      return null;
    }
  }

  Future<bool> updateUserProfile(String userId, Map<String, dynamic> profileData) async {
    try {
      // 获取当前用户数据
      final currentUser = _prefsService.getObject(SharedPreferencesService.keyUser);
      if (currentUser == null) return false;

      // 更新数据
      final updatedData = {
        ...currentUser,
        ...profileData,
        'updated_at': DateTime.now().toIso8601String(),
      };

      // 保存更新后的数据
      return await _prefsService.setObject(SharedPreferencesService.keyUser, updatedData);
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }

  Future<Map<String, dynamic>?> getUserProfile(String userId) async {
    try {
      // 由于是单机应用，直接获取存储的用户数据
      final user = _prefsService.getObject(SharedPreferencesService.keyUser);
      if (user != null && user['id'] == userId) {
        return user;
      }
      return null;
    } catch (e) {
      // 移除print语句，返回null表示操作失败
      return null;
    }
  }

  Future<bool> logoutUser(String userId) async {
    try {
      // 清除用户会话信息
      return true;
    } catch (e) {
      // 移除print语句，返回false表示操作失败
      return false;
    }
  }
}